import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
    isLoggedIn: !!localStorage.getItem('token')
  }),
  
  getters: {
    hasToken: (state) => !!state.token,
    username: (state) => state.userInfo?.username || '',
    userId: (state) => state.userInfo?.userId || ''
  },
  
  actions: {
    // 设置登录信息
    setLoginInfo(data) {
      this.token = data.token
      this.userInfo = {
        userId: data.userId,
        username: data.username,
        remark: data.remark
      }
      this.isLoggedIn = true
      
      // 保存到localStorage
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    
    // 清除登录信息
    clearLoginInfo() {
      this.token = ''
      this.userInfo = null
      this.isLoggedIn = false
      
      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
    
    // 登出
    logout() {
      this.clearLoginInfo()
      // 跳转到登录页
      window.location.href = '/login'
    }
  }
})
